package models.admin;

import models.BaseModel;
import org.apache.commons.lang.StringEscapeUtils;
import play.Logger;
import util.common.ConvertUtil;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
import java.util.List;

/**
 * Created by liming on 16/7/4.
 */
@Entity
@Table(name = "admin_role_operate")
public class AdminRoleOperate extends BaseModel {
    /**
     * 关联角色
     */
    @ManyToOne
    @JoinColumn(name = "admin_role_id")
    public AdminRole adminRole;

    /**
     * 角色业务操作
     */
    @ManyToOne
    @JoinColumn(name = "admin_biz_operate_id")
    public AdminBusinessOperate adminBusinessOperate;

    public AdminRoleOperate() {

    }

    public AdminRoleOperate(AdminRole adminRole, Long operateId) {
        this.adminRole = adminRole;
        this.adminBusinessOperate = new AdminBusinessOperate();
        this.adminBusinessOperate.id = operateId;
        this.createAt = new Date();
    }

    /**
     * 根据角色ID删除角色操作
     *
     * @param roleId
     */
    public static void deleteByRoleId(long roleId) {
        AdminRoleOperate.delete("adminRole.id = ?", roleId);
    }

    /**
     * 根据角色Id加载角色操作
     *
     * @param roleId
     * @return
     */
    public static List<AdminRoleOperate> loadByRoleId(long roleId) {
        return AdminRoleOperate.find("adminRole.id = ?", roleId).fetch();
    }

    /**
     * 验证当前用户是否有当前操作权限
     * 目前先用数据库验证,之后有性能问题考虑用户登录时权限全部加载到缓存,在程序中校验
     */
    public final static String IS_SECURE_SQL = "select count(1) from admin_user_role x" +
            " left join admin_role a on x.admin_role_id = a.id" +
            " left join admin_role_operate b on a.id = b.admin_role_id" +
            " left join admin_business_operate c on b.admin_biz_operate_id = c.id" +
            " left join admin_business d on c.business_id = d.id" +
            " where x.admin_user_id = %d and d.controller = '%s' " +
            " and ((c.operate_type = 'SYSTEM' and '%s' like CONCAT(c.filterKey,'%%')) or (c.operate_type='CUSTOM' and c.filterKey='%s'))";

    public static Boolean isSecure(long userId, String controller, String actionMethod) {
        controller = StringEscapeUtils.escapeSql(controller);
        actionMethod = StringEscapeUtils.escapeSql(actionMethod);
        long authCount = ConvertUtil.toLong(em().createNativeQuery(String.format(IS_SECURE_SQL, userId, controller, actionMethod, actionMethod)).getSingleResult());

        return authCount > 0;
    }
}
